<template>
  <div class="dept">
    <el-row :gutter="10">
      <el-col :xs="24" :sm="5">
        <el-card class="box-card">
          <div class="app-container">
            <div class="filter-container">
              <el-button class="filter-item" type="primary" style="margin: 0px; padding: 10px;" icon="el-icon-document-add" @click="add">
                新增
              </el-button>
              <el-button class="filter-item" type="success" style="margin: 0px; padding: 10px;" icon="el-icon-refresh-left" @click="reset">
                重置
              </el-button>
              <el-button class="filter-item" type="danger" style="margin: 0px; padding: 10px;" icon="el-icon-delete" @click="toDelte">
                删除
              </el-button>
              <el-input v-model="deptName" placeholder="请输入部门名称" class="filter-item search-item" style="width:100%; margin-top: 3%;" @keyup.native="search" />
              <div id="searchtree-eletree" class="tree-style">
                <el-tree
                  ref="girdTree"
                  :data="girdTree"
                  :default-expand-all="true"
                  :check-strictly="true"
                  :expand-on-click-node="false"
                  show-checkbox
                  :accordion="false"
                  node-key="id"
                  highlight-current
                  :filter-node-method="searchFilterNode"
                  @node-click="nodeClick"
                  @check-change="currentNodeCheck"
                />
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="19" style="margin: 0px; padding: 0px;">
        <el-row :gutter="10">
          <el-card class="box-card">
            <el-row :gutter="10">
              <el-col :xs="24" :sm="24">
                <div class="div-query">
                  <div class="collapse">
                    <div class="collapse-header" @click="panelActive = !panelActive">
                      <i
                        class="collapse-header-icon"
                        :class="[
                          panelActive ? 'el-icon-caret-bottom' : 'el-icon-caret-top',
                        ]"
                      />
                      {{ panelActive ? '隐藏' : '展开' }}查询条件
                    </div>
                    <div class="collapse-content">
                      <el-collapse-transition>
                        <div v-show="panelActive">
                          <el-form ref="form" :model="searchModel" label-position="right" label-width="100px">
                            <el-row style="margin-top: 8px;">
                              <el-col :span="8">
                                <el-form-item label="所属省:" prop="province">
                                  <el-select v-model="searchModel.province" placeholder="请选择所属省" filterable clearable style="width: 100%;" @change="getCitymodelChange(searchModel.province)">
                                    <el-option v-for="item of provinceList" :key="item.label" :label="item.label" :value="item.value" />
                                  </el-select>
                                </el-form-item>
                              </el-col>
                              <el-col :span="8">
                                <el-form-item label="所属市:" prop="city">
                                  <el-select v-model="searchModel.city" placeholder="请选择所属市" filterable clearable style="width: 100%;" @change="getCountyModelChange(searchModel.city)">
                                    <el-option v-for="item of cityList" :key="item.label" :label="item.label" :value="item.value" />
                                  </el-select>
                                </el-form-item>
                              </el-col>
                              <el-col :span="8">
                                <el-form-item label="所属区县:" prop="county">
                                  <el-select v-model="searchModel.county" placeholder="请选择所属区县" filterable clearable style="width: 100%;">
                                    <el-option v-for="item of countyList" :key="item.label" :label="item.label" :value="item.value" />
                                  </el-select>
                                </el-form-item>
                              </el-col>
                            </el-row>
                            <el-row>
                              <el-col :span="8" style="margin-top: -1%;">
                                <el-form-item label="所属部门:" prop="deptGuid">
                                  <treeselect
                                    v-model="deptGuidList"
                                    :multiple="false"
                                    :options="deptGuidTree"
                                    :normalizer="normalizer"
                                    clear-value-text="删除"
                                    placeholder="请选择所属部门"
                                    style="{width:100%, height: 35px }"
                                    @select="deptGuidSelectChange"
                                  />
                                  <!-- <el-input v-model="searchModel.deptGuid" /> -->
                                </el-form-item>
                              </el-col>
                              <el-col :span="8" style="margin-top: -1%;">
                                <el-form-item label="网格名称:" prop="name">
                                  <el-input v-model="searchModel.name" />
                                </el-form-item>
                              </el-col>
                              <el-col :span="8" style="margin-top: -0.95%; padding-left: 2.6%;">
                                <el-button type="primary" icon="el-icon-search" style="margin: 0px; padding: 10px;" @click="query">查询</el-button>
                                <el-button type="success" icon="el-icon-refresh-left" style="margin: 0px; padding: 10px;" @click="resetTableList">重置</el-button>
                                <el-button icon="el-icon-refresh-left" style="margin: 0px; padding: 10px;" @click="refresh">刷新</el-button>
                              </el-col>
                            </el-row>
                          </el-form>
                        </div>
                      </el-collapse-transition>
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col :xs="24" :sm="24">
                <el-table
                  v-loading="loading"
                  element-loading-text="数据加载中..."
                  :data="dataList"
                  :header-cell-style="tableHeaderColor"
                  stripe
                  border
                  size="small"
                  style="width: 100%"
                >
                  <el-table-column
                    fixed="left"
                    :label="$t('table.operation')"
                    align="center"
                    width="250"
                  >
                    <template slot-scope="scope">
                      <el-button type="success" style="margin: 0px; padding: 6px;" icon="el-icon-view" @click="toDetail(scope.row)">详情</el-button>
                      <el-button type="primary" style="margin: 0px; padding: 6px;" icon="el-icon-edit" @click="toEdit(scope.row)">编辑</el-button>
                       <el-button type="info" style="margin: 0px; padding: 6px;" icon="el-icon-edit" @click="bindDevice(scope.row)">关联设备</el-button>
                      <!-- <el-button type="danger" style="margin: 0px; padding: 5px;" size="small" icon="el-icon-delete" @click="toDelte(scope.row.guid)">{{ $t('common.delete') }}</el-button> -->
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="name"
                    label="网格名称"
                    width="150"
                  />
                  <el-table-column
                    prop="parentName"
                    label="上级网格"
                    width="200"
                    align="center"
                  />
                  <el-table-column
                    prop="deptName"
                    label="所属部门"
                    width="200"
                  />
                  <el-table-column
                    prop="fullPathText"
                    label="部门路径"
                    width="400"
                  />
                  <el-table-column
                    prop="level"
                    label="网格层级"
                    width="100"
                  />
                  <el-table-column
                    prop="province"
                    label="所属省"
                    width="120"
                  />
                  <el-table-column
                    prop="city"
                    label="所属市"
                    width="120"
                  />
                  <el-table-column
                    prop="county"
                    label="所属区县"
                    width="120"
                  />
                  <el-table-column
                    prop="longitude"
                    label="经度"
                    width="100"
                  />
                  <el-table-column
                    prop="latitude"
                    label="纬度"
                    width="100"
                  />
                  <el-table-column
                    prop="orderNum"
                    label="排序"
                    width="100"
                  />
                </el-table>
              </el-col>
              <el-col :offset="8">
                <el-pagination
                  :current-page="searchModel.pageSize"
                  :page-sizes="[10, 20, 50, 100, 120]"
                  :page-size="searchModel.pageNum"
                  layout="total, prev, pager, next, jumper, sizes"
                  :total="total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </el-col>
            </el-row>
          </el-card>
        </el-row>
      </el-col>
    </el-row>
    <grid-form
      v-if="addGridVisible"
      ref="girdAdd"
      :visible.sync="addGridVisible"
      :grid-form-type="gridFormType"
      :el-icon-type="elIconType"
      :form-data="formData"
      :center="center"
      :rec-keyword="keyword"
      @submit="afterSubmit"
    />
    <grid-detail
      v-if="gridDetailVisible"
      ref="gridDetail"
      :visible.sync="gridDetailVisible"
      :params-detail="paramsDetail"
    />


  </div>
</template>

<script>
import GridDetail from './component/grid-detail'
import GridForm from './component/grid-form'

import GridManageApi from '../../../../api/grid-manage'
import recDataGridParams from './grid-params'
import dataTableMixins from '@/mixins/data-table-mixins'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: 'GirdManager',
  components: {
    Treeselect,
    GridDetail,
    GridForm,

  },
  mixins: [dataTableMixins],
  data() {
    return {
      deptName: '',
      // 树
      searchTreeData: [],
      defaultEexpandedkeys: [0], // 默认展开一级树节点
      // 查询栏
      searchInput: '',
      searchIndex: null,
      girdTree: this.initGirdTree(),
      deptGuidTree: this.initDeptGuidTree(),
      girdDetailVisible: false,

      guidList: [],
      cityList: [],
      countyList: [],
      provinceList: [],
      elIconType: 'el-icon-document-add',
      gridFormType: '新增',
      addGridVisible: false,
      formData: {},
      dialogVisible: false,
      loading: false,
      total: 0,
      dataList: [],
      searchModel: { ...recDataGridParams.recSearch },
      deptGuidList: null,
      addGridVisiable: false,
      paramsDetail: {},
      gridDetailVisible: false,
      zoom: 15,
      gridrow:{},
      // 地图你解析方法实例
      // 搜索关键字
      keyword: '',
      // 初始化地图中心点
      center: {
        lng: 108.30,
        lat: 22.83,
        showFlag: false
      },
      deviceList:[]
    }
  },
  watch: {
    deptName(val) {
      this.$refs.girdTree.filter(val)
    }
  },
  created() {
    this.getDataList()
    this.getPorvinceModelChange()
  },
  mounted() {
    this.keyword = ''
    this.initGirdTree()
    this.initDeptGuidTree()
  },
  methods: {
    // 设备绑定
    bindDevice(value){

    },
    getDataList() {
      console.log('searchModel:', this.searchModel)
      this.loading = true
      const api = 'main/grid/detailList?id=' + this.searchModel.id + '&deptGuid=' + this.searchModel.deptGuid + '&longitude=' + this.searchModel.longitude + '&latitude=' + this.searchModel.latitude +
      '&name=' + this.searchModel.name + '&order=' + this.searchModel.order + '&orderNum=' + this.searchModel.orderNum + '&pageNum=' + this.searchModel.pageNum +
      '&pageSize=' + this.searchModel.pageSize + '&parentGuid=' + this.searchModel.parentGuid + '&createTimeTo=' + this.searchModel.createTimeTo +
      '&createTimeFrom=' + this.searchModel.createTimeFrom + '&province=' + this.searchModel.province + '&city=' + this.searchModel.city + '&county=' + this.searchModel.county +
      '&field=' + this.searchModel.field + '&zoonId=' + this.searchModel.zoonId + '&isDel=' + this.searchModel.isDel + '&fullPath=' + this.searchModel.fullPath +
      '&fullPathText=' + this.searchModel.fullPathText + '&guid=' + this.searchModel.guid + '&guids=' + this.searchModel.guids + '&level=' + this.searchModel.level
      this.$get(api).then(res => {
        console.log('res:', res)
        if (res.status === 200) {
          const resJson = res.data
          this.dataList = resJson.data.rows
          this.total = resJson.data.total
          this.loading = false
        } else {
          this.$message({
            showClose: true,
            message: res.statusText,
            type: 'error',
            duration: 4000
          })
          this.loading = false
        }
      })
    },
    initGirdTree() {
      GridManageApi.getGridTree().then(res => {
        // console.log('res:', res)
        if (res.status === 200) {
          const resJson = res.data
          this.girdTree = resJson.data.rows
          if (this.girdTree && this.girdTree.length !== 0) {
            this.girdTree.forEach((ele, idx, arr) => {
              arr[idx].checked = false
            })
          } else {
            this.girdTree = []
          }
          console.log('girdTree:', this.girdTree)
        } else {
          this.$message({
            showClose: true,
            message: res.statusText,
            type: 'error',
            duration: 4000
          })
        }
      })
    },
    normalizer(node) {
      // 去掉children=null的属性
      if (node.children == null || node.children === 'null') {
        delete node.children
      }
    },
    getPorvinceModelChange() {
      const api = 'main/position?level=' + 1
      this.$get(api).then(res => {
        if (res.status === 200) {
          const resJson = res.data
          const list = resJson.data
          this.provinceList = []
          list.forEach(ele => {
            this.provinceList.push({
              label: ele.positionName,
              value: ele.codeId
            })
          })
          // console.log('provinceList:', this.provinceList)
        } else {
          this.$message({
            showClose: true,
            message: res.statusText,
            type: 'error',
            duration: 4000
          })
        }
      })
    },
    getCitymodelChange(codeId) {
      const api = 'main/position?parentCodeId=' + codeId
      this.searchModel.city = ''
      this.searchModel.county = ''
      this.$get(api).then(res => {
        if (res.status === 200) {
          const resJson = res.data
          const list = resJson.data
          this.cityList = []
          list.forEach(ele => {
            this.cityList.push({
              label: ele.positionName,
              value: ele.codeId
            })
          })
        } else {
          this.$message({
            showClose: true,
            message: res.statusText,
            type: 'error',
            duration: 4000
          })
        }
      })
    },
    getCountyModelChange(codeId) {
      const api = 'main/position?parentCodeId=' + codeId
      this.searchModel.county = ''
      this.$get(api).then(res => {
        if (res.status === 200) {
          const resJson = res.data
          const list = resJson.data
          this.countyList = []
          list.forEach(ele => {
            this.countyList.push({
              label: ele.positionName,
              value: ele.codeId
            })
          })
        } else {
          this.$message({
            showClose: true,
            message: res.statusText,
            type: 'error',
            duration: 4000
          })
        }
      })
    },
    getCurrentNodedata(id) {
      this.searchModel.guid = id
      this.$get('main/grid', this.searchModel).then(res => {
        console.log('res:', res)
      })
    },
    initDeptGuidTree() {
      this.deptGuidTree = []
      this.$get('system/dept').then((r) => {
        this.deptGuidTree = r.data.data.rows
      })
    },
    deptGuidSelectChange(event) {
      console.log('deptGuidSelect:', event)
      this.searchModel.deptGuid = event.guid
      this.searchModel.deptName = event.label
    },
    add() {
      this.gridFormType = '新增'
      this.addGridVisible = true
      this.center.showFlag = false
      this.keyword = ''
      this.elIconType = 'el-icon-document-add'
    },
    toEdit(data) {
      this.gridFormType = '修改'
      this.addGridVisible = true
      this.center.showFlag = false
      this.keyword = ''
      this.elIconType = 'el-icon-edit'
      this.formData = data
    },
    toDetail(data) {
      this.paramsDetail = data
      this.gridDetailVisible = true
    },
    search() {
      this.$refs.girdTree.filter(this.deptName)
    },
    reset() {
      this.initGirdTree()
      this.resetSearchModelData()
      this.getDataList()
    },
    nodeClick(data) {
      console.log('nodeData1111:', data)
      this.resetSearchModelData()
      this.searchModel.fullPath = data.fullPath
      this.getDataList()
    },
    currentNodeCheck(data, checked, childrenNodeChecked) {
      console.log('data:', data)
      console.log('checked:', checked)
      console.log('childrenNode:', childrenNodeChecked)
      if (checked) {
        this.guidList.push({
          guid: data.guid,
          checked: checked
        })
      } else {
        this.guidList.forEach((ele, idx, arr) => {
          if (ele.guid === data.guid) {
            arr.splice(ele, 1)
          }
        })
      }
      console.log('guidList:', this.guidList)
      this.resetSearchModelData()
      this.searchModel.fullPath = data.fullPath
      this.getDataList()
    },
    searchFilterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    afterSubmit(formType) {
      this.resetSearchModelData()
      this.getDataList()
      this.initGirdTree()
    },
    toDelte() {
      const list = []
      this.guidList.forEach(ele => {
        list.push(ele.guid)
      })
      const guid = list.join(',')
      console.log('guid1:', guid)
      this.$confirm('此操作将删当前节点部门,及其所属的所有子节点部门 确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'btnConfirmStyle',
        cancelButtonClass: 'btnCancelStyle'
      }).then(() => {
        const api = 'main/grid/' + guid
        console.log('api:', api)
        this.$delete(api).then(res => {
          console.log('res:', res)
          if (res.status === 200) {
            console.log('res:', res)
            this.resetSearchModelData()
            this.getDataList()
            this.initGirdTree()
            this.$message({
              showClose: true,
              message: '删除成功！',
              type: 'success',
              duration: 4000
            })
          } else {
            this.$message({
              showClose: true,
              message: res.statusText,
              type: 'error',
              duration: 4000
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    resetSearchModelData() {
      this.searchModel.id = ''
      this.searchModel.deptGuid = ''
      this.searchModel.longitude = 0
      this.searchModel.latitude = 0
      this.searchModel.name = ''
      this.searchModel.order = ''
      this.searchModel.orderNum = 0
      this.searchModel.pageNum = 1
      this.searchModel.pageSize = 10
      this.searchModel.parentGuid = ''
      this.searchModel.createTimeTo = ''
      this.searchModel.createTimeFrom = ''
      this.searchModel.province = ''
      this.searchModel.field = ''
      this.searchModel.city = ''
      this.searchModel.county = ''
      this.searchModel.zoonId = ''
      this.searchModel.fullPath = ''
      this.searchModel.fullPathText = ''
      this.searchModel.guid = ''
      this.searchModel.guids = ''
      this.searchModel.isDel = 0
      this.searchModel.level = 0
      this.deptGuidList = null
    },
    deleteTipClose() {
      this.deleteTipDialog = false
    },
    query() {
      if (this.searchModel.province !== '') {
        if (this.searchModel.city !== '') {
          if (this.searchModel.county !== '') {
            this.searchModel.zoonId = this.searchModel.county
          } else {
            this.searchModel.county = ''
            this.searchModel.zoonId = this.searchModel.city
          }
        } else {
          this.searchModel.county = ''
          this.searchModel.zoonId = this.searchModel.province
        }
      }
      this.searchModel.pageNum = 1
      this.getDataList()
    },
    resetTableList() {
      this.resetSearchModelData()
      this.query()
    },
    refresh() {
      this.resetTableList()
    },
    tableHeaderColor({ rowIndex }) {
      return 'background-color: #fafafa'
    },
    handleSizeChange(val) {
      this.searchModel.pageSize = val
    },
    handleCurrentChange(val) {
      this.searchModel.pageNum = val
    }
  }
}
</script>

<style lang='scss' >
@import '../../../../styles/custom.scss';
</style>

<style>
  .app-container {
    padding: 0px; margin: 0px;
  }
  /* .el-button {
    margin-right: 0px;
  } */
  .box-card {
    margin: 0px; padding: 0px;
  }
  .el-tree {
    padding: 10px;
    background: #fafafb; border: 2px solid #dfe6ec; border-radius: 5px;
  }
  .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
   background-color:  #b0c4de;
  }
  .treeselect-main {
    width: 204px;
    line-height: 28px;
  }
  .vue-treeselect__placeholder {
    line-height: 28px;
  }
  .vue-treeselect__control {
    height: 28px !important;
  }
 .el-divider--horizontal {
    margin: 5px 0px 10px 0px;
  }
 .el-collapse-item__content {
   margin-bottom: 0px; padding-bottom: 0px;
 }
 .serachinput{
   height: 40px;
 }
 .btnConfirmStyle {
   background: #f04134 !important;
   border: #f04134 !important;
 }
 .btnCancelStyle {
   margin-right: 10px !important;
 }
 /*列表查询条件收缩样式-----------------------------------------------------------------------------------------------------*/
  .div-query {
      background: #fafafb;
      border-radius: 2px;
      border: 1px solid #e3e3e3;
      padding: 0 5px;
      margin-bottom: 15px;
  }
  .collapse {
      background: #fafafb;
      border: 0;
      border-radius: 4px;
      margin-bottom: 6px;
  }
  .collapse-header {
      position: relative;
      padding: 3px 16px 3px 40px;
      color: rgba(0, 0, 0, 0.85);
      line-height: 22px;
      cursor: pointer;
      transition: all 0.3s;
      border-bottom: 1px solid #e8e8e8;
  }
  .collapse-header-icon {
      position: absolute;
      top: 50%;
      left: 16px;
      transform: translateY(-50%);
  }
  .collapse-content {
      color: rgba(0, 0, 0, 0.65);
      padding: 0 12px;
  }
  .el-tree-node:focus>.el-tree-node__content{
    color: #409eff;
  }
</style>

